package com.lindroy.jetpacknotes.paging

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import com.lindroy.jetpacknotes.R
import com.lindroy.jetpacknotes.logic.model.MainViewModel
import com.lindroy.jetpacknotes.paging.adapter.ArticleAdapter
import com.lindroy.jetpacknotes.paging.adapter.FootAdapter
import com.lindroy.jetpacknotes.paging.adapter.HeaderAdapter
import kotlinx.android.synthetic.main.activity_paging3.*
import kotlinx.coroutines.flow.collect


class Paging3Activity : AppCompatActivity() {
    private val mainViewModel by lazy { ViewModelProvider(this)[MainViewModel::class.java] }

    private val articleAdapter = ArticleAdapter()
    private val footAdapter = FootAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_paging3)
        //添加Android自带的分割线
        rvArticle.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        rvArticle.adapter = articleAdapter
//        rvArticle.adapter = articleAdapter.withLoadStateFooter(footAdapter)
        //header是用来加载上一页的，这里的例子暂时没有起作用
        rvArticle.adapter =
            articleAdapter.withLoadStateHeaderAndFooter(HeaderAdapter(), footAdapter)
        getArticles()

        articleAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    rvArticle.isVisible = true
                    progressBar.isGone = true
                }
                is LoadState.Loading -> {
                    rvArticle.isGone = true
                    progressBar.isVisible = true
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    progressBar.visibility = View.INVISIBLE
                    Toast.makeText(this, "加载出错: ${state.error.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }

        footAdapter.setOnRetryClickListener {
            articleAdapter.retry()
        }
    }

    private fun getArticles() {
        lifecycleScope.launchWhenResumed {
            mainViewModel.pagingData.collect {
                articleAdapter.submitData(pagingData = it)
            }
        }
    }
}